<template>
  <div v-loading="loading" class="activeProfile">
    <div v-if="BindForm" class="cus-update">
      <el-form ref="form" :model="BindForm" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="活动名称:" prop="actName">
          <el-col :span="24">
            <el-input v-model="BindForm.actName" :disabled="true" maxlength="20" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="活动描述:" prop="actDesc">
          <el-col :span="24">
            <el-input v-model="BindForm.actDesc" :disabled="true" maxlength="30" class="cus-input" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="活动时间:" prop="actTimes">
          <el-col :span="24">
            <el-date-picker
              v-model="BindForm.actTimes"
              :disabled="true"
              type="datetimerange"
              range-separator="至"
              start-placeholder="活动开始时间"
              end-placeholder="活动结束时间"
              align="center"
              clearable
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="活动商品:" prop="actGoodsType">
          <el-col :span="24">
            <!--            <el-button-->
            <!--              v-if="BindForm.actGoodsType == 0"-->
            <!--              type="text"-->
            <!--              style="margin-right: 30px;"-->
            <!--              @click="$refs.addActGoodsDialog.show()"-->
            <!--            >添加活动商品</el-button>-->
            <el-radio-group v-model="BindForm.actGoodsType" :disabled="true">
              <el-radio :label="0">部分商品</el-radio>
              <el-radio :label="1">全部商品</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.actGoodsType == 0 && BindForm.actGoodsList && BindForm.actGoodsList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.actGoodsList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                label="操作"-->
              <!--                header-align="center"-->
              <!--                align="center"-->
              <!--                fixed="right"-->
              <!--                width="100"-->
              <!--                :resizable="false"-->
              <!--              >-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-button size="small" type="danger" @click="deleteActGoods(scope.$index)">删除</el-button>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item label="活动类型:" prop="actType">
          <el-col :span="24">
            <el-radio-group v-model="BindForm.actType" :disabled="true">
              <el-radio :label="0">推荐活动</el-radio>
              <el-radio :label="1">组合活动</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="打包商品:" prop="packGoodsList">
          <!--          <el-col :span="24">-->
          <!--            <el-button-->
          <!--              type="text"-->
          <!--              @click="$refs.activeProfileGoodsDialog.show()"-->
          <!--            >添加打包商品</el-button>-->
          <!--          </el-col>-->
          <el-col v-if="BindForm.packGoodsList && BindForm.packGoodsList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.packGoodsList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="商品编号"
                prop="goodsId"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.goodsImg" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="goodsName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="默认勾选"
                align="center"
                width="130"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-radio-group v-model="BindForm.packGoodsList[scope.$index].checked" size="mini" @change="checkedChange($event, scope.$index)">
                    <el-radio-button :label="0">否</el-radio-button>
                    <el-radio-button :label="1">是</el-radio-button>
                  </el-radio-group>
                </template>
              </el-table-column>
              <el-table-column
                label="是否必选"
                align="center"
                width="130"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-radio-group v-model="BindForm.packGoodsList[scope.$index].required" size="mini" @change="requiredChange($event, scope.$index)">
                    <el-radio-button :label="0">否</el-radio-button>
                    <el-radio-button :label="1">是</el-radio-button>
                  </el-radio-group>
                </template>
              </el-table-column>
              <!--              <el-table-column-->
              <!--                label="操作"-->
              <!--                header-align="center"-->
              <!--                align="center"-->
              <!--                fixed="right"-->
              <!--                width="100"-->
              <!--                :resizable="false"-->
              <!--              >-->
              <!--                <template slot-scope="scope">-->
              <!--                  <el-button size="small" type="danger" @click="deletePackGoods(scope.$index)">删除</el-button>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item label="活动门店:" prop="actStoreType">
          <el-col :span="24">
            <el-button
              v-if="BindForm.actStoreType == 0"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加支持门店</el-button>
            <el-button
              v-else-if="BindForm.actStoreType == 1"
              style="margin-right: 30px;"
              type="text"
              @click="$refs.addStoreDialog.show()"
            >添加不支持门店</el-button>
            <el-radio-group v-model="BindForm.actStoreType">
              <el-radio :label="0">支持部分门店</el-radio>
              <el-radio :label="1">不支持的门店</el-radio>
              <el-radio :label="2">支持全部门店</el-radio>
            </el-radio-group>
          </el-col>
          <el-col v-if="BindForm.actStoreType != 2 && BindForm.storeList && BindForm.storeList.length > 0" :span="24" style="margin-top: 10px;">
            <el-table
              :data="BindForm.storeList"
              border
              style="width: 100%"
              max-height="400"
            >
              <el-table-column
                label="门店编号"
                prop="id"
                align="center"
                width="130"
                :resizable="false"
                fixed="left"
              />
              <el-table-column
                label="门店名称"
                prop="storeName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="门店地址"
                prop="address"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="操作"
                header-align="center"
                align="center"
                fixed="right"
                width="100"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="danger" @click="deleteStore(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">更新活动配置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <AddGoodsDialog ref="addActGoodsDialog" @select="addActGoods" />
    <AddGoodsDialog ref="activeProfileGoodsDialog" @select="activeProfileGoods" />
    <AddStoreDialog ref="addStoreDialog" @select="addStore" />
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import AddGoodsDialog from '../../../../components/AddGoodsDialog/index'
import AddStoreDialog from '../../../../components/AddStoreDialog/index'
import { detailPackAct, updatePackAct } from '@/api/market'
import TableColumnGoodsImage from '../../../../components/TableColumnGoodsImage/index'
export default {
  name: 'ActiveProfile',
  components: { TableColumnGoodsImage, AddStoreDialog, AddGoodsDialog },
  props: {
    id: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    var validateActGoods = (rule, value, callback) => {
      if (this.BindForm.actGoodsType === 0 && this.BindForm.actGoodsList.length <= 0) {
        callback(new Error('请至少添加一个活动商品'))
      } else {
        callback()
      }
    }

    var validatePackGoods = (rule, value, callback) => {
      if (this.BindForm.packGoodsList.length <= 0) {
        callback(new Error('请至少添加一个打包商品'))
      } else {
        callback()
      }
    }

    var validateStore = (rule, value, callback) => {
      if (this.BindForm.actStoreType !== 2 && this.BindForm.storeList.length <= 0) {
        callback(new Error('请至少添加一个门店'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      BindForm: null,
      rules: {
        actName: [{ required: true, message: '请输入活动名称', trigger: 'change' }],
        actDesc: [{ required: true, message: '请输入活动描述', trigger: 'change' }],
        actTimes: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        actGoodsType: [{ required: true, message: '请选择活动商品', trigger: 'change' }, { validator: validateActGoods, trigger: 'blur' }],
        actType: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        packGoodsList: [{ required: true, message: '请至少添加一个打包商品', trigger: 'change' }, { validator: validatePackGoods, trigger: 'blur' }],
        actStoreType: [{ required: true, message: '请选择活动门店', trigger: 'change' }, { validator: validateStore, trigger: 'blur' }]
      }
    }
  },
  created() {
    const vm = this

    vm.loading = true

    detailPackAct({
      id: vm.id
    }).then(res => {
      vm.loading = false
      const data = res.data.data
      data.actTimes = [
        data.startTime,
        data.endTime
      ]
      vm.BindForm = data
    }).catch(res => {
      vm.loading = false
      if (res && res.data && res.data.errno !== 0) {
        this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
      }
    })
  },
  methods: {
    submit() {
      const vm = this
      vm.$refs.form.validate((valid) => {
        if (valid) {
          vm.$confirm('确定更新打包活动配置吗？', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            vm.update()
          }).catch(() => {})
        }
      })
    },
    update() {
      const vm = this

      const loadingInstance = Loading.service({ fullscreen: true })
      const data = {
        id: vm.id
      }

      data['packGoodsList'] = vm.BindForm.packGoodsList.map(item => {
        return vm.$XEUtils.pick(item, ['goodsId', 'checked', 'required'])
      })

      data['actStoreType'] = vm.BindForm.actStoreType

      if (data['actStoreType'] === 0 || data['actStoreType'] === 1) {
        data['storeList'] = vm.BindForm.storeList.map(item => {
          return vm.$XEUtils.pick(item, ['id'])
        })
      }

      updatePackAct(data).then(res => {
        loadingInstance.close()
        vm.$message.success('更新打包活动成功')
      }).catch(res => {
        loadingInstance.close()
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    addActGoods(goods) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.actGoodsList, item => item.goodsId === goods.goodsId)

      if (res) {
        vm.$message.warning('商品已存在，无需重复添加活动商品')
        return
      }

      vm.BindForm.actGoodsList.push(vm.$XEUtils.clone(goods, true))
      vm.$refs.form.validateField('actGoodsType')
    },
    deleteActGoods(index) {
      const vm = this

      vm.BindForm.actGoodsList.splice(index, 1)
      vm.$refs.form.validateField('actGoodsType')
    },
    activeProfileGoods(goods) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.packGoodsList, item => item.goodsId === goods.goodsId)

      if (res) {
        vm.$message.warning('商品已存在，无需重复添加打包商品')
        return
      }

      goods.checked = 0
      goods.required = 0
      vm.BindForm.packGoodsList.push(vm.$XEUtils.clone(goods, true))
      vm.$refs.form.validateField('packGoodsList')
    },
    deletePackGoods(index) {
      const vm = this

      vm.BindForm.packGoodsList.splice(index, 1)
      vm.$refs.form.validateField('packGoodsList')
    },
    checkedChange(val, index) {
      const vm = this
      if (val === 0) {
        vm.BindForm.packGoodsList[index].required = 0
      }
    },
    requiredChange(val, index) {
      const vm = this
      if (val === 1) {
        vm.BindForm.packGoodsList[index].checked = 1
      }
    },
    addStore(store) {
      const vm = this

      const res = vm.$XEUtils.find(vm.BindForm.storeList, item => item.id === store.id)

      if (res) {
        vm.$message.warning('门店已存在，无需重复添加门店')
        return
      }

      vm.BindForm.storeList.push(vm.$XEUtils.clone(store, true))
      vm.$refs.form.validateField('actStoreType')
    },
    deleteStore(index) {
      const vm = this

      vm.BindForm.storeList.splice(index, 1)
      vm.$refs.form.validateField('actStoreType')
    }
  }
}
</script>

<style lang="scss" scoped>
  .activeProfile {
    .cus-update {
      padding: 20px 30px;
      padding-bottom: 0px;
      margin-bottom: 30px;
      border: 1px solid #eee;

      .cus-input {
        max-width: 400px;
      }
    }
  }
</style>
